import React, { Component } from 'react';
import {
  Affix,
  Button,
  Form,
  Input,
  Select,
  DatePicker,
  Spin,
  Row,
  Col,
  InputNumber,
  message
} from 'antd';
import { messages, queryCurrencyPrecision } from 'share/common';
import Chooser from 'components/chooser';
import expenseReportService from '../../expense-report/expense-report.service';
import moment from 'moment';
import paymentService from '../payment-service';
import constants from "share/constants";

const { TextArea } = Input;
const { Option } = Select;

@Form.create()
class NewPayInfo extends Component {

  payTypes = [{ type: 1002, name: messages('expense-18.key12')/*员工*/ }, { type: 1001, name: messages('expense-18.key13')/*供应商*/ }];

  constructor(props) {
    super(props);

    class WrapInput extends Component {
      handleInputNumber = (target) => {
        const { value, onChange } = this.props;
        onChange({ ...value, amount: target });
      };

      render() {
        const { value = {} } = this.props;
        return <Row style={{ width: '66%' }}>
          <Col span={8}>
            <Input
              disabled
              value={value.paymentCurrencyCode}
            />
          </Col>
          <Col span={15} offset={1}>
            <InputNumber
              step={0.01}
              precision={queryCurrencyPrecision(value.paymentCurrencyCode)}
              min={0}
              style={{ width: '100%' }}
              value={value.amount}
              onChange={this.handleInputNumber}
            />
          </Col>
        </Row>;
      }
    }

    this.state = {
      amountExtra: '',
      paymentMethod: '',
      formArray: [{
        dataIndex: 'businessCode',
        title: messages('expense-18.key8')/*关联报销单*/,
        required: true,
        component: Chooser,
        params: {
          type: 'contact-expense-report',
          single: true,
          onChange: this.handleExpenseChange,
          valueKey: 'id',
          labelKey: 'businessCode',
          listExtraParams: {
            paymentRequestOID: props.paymentRequestOID
          },
        }
      }, {
        dataIndex: 'contractHeaderId',
        title: messages('expense-18.key29')/*关联合同*/,
        component: Input,
        params: {
          disabled: true
        }
      }, {
        dataIndex: 'realPaymentAmount',
        title: messages('expense-18.key4')/*付款金额*/,
        component: WrapInput,
        otherRules: [
          {
            validator: this.handleAmountValidator
          },
          {
            required: true,
            message: messages('common.please.input')/*请输入temp2*/ + messages('expense-18.key4')/*付款金额*/
          }],
        extra: this.amountExtra
      }, {
        dataIndex: 'payeeType',
        title: messages('expense-18.key30')/*收款方类型*/,
        required: true,
        component: Select,
        children: this.payTypes.map(item => <Option key={item.type}>{item.name}</Option>),
        params: {
          disabled: true
        }
      }, {
        dataIndex: 'payeeName',
        title: messages('expense-18.key31')/*收款方*/,
        required: true,
        component: Input,
        params: {
          disabled: true
        }
      }, {
        dataIndex: 'payeeBankAccountNumber',
        title: messages('expense-18.key32')/*收款方银行账号*/,
        component: Select,
        params: {
          onChange: this.handlePayeeBankAccountChange
        }
      }, {
        dataIndex: 'payeeBankAccountName',
        title: messages('expense-18.key33')/*收款方户名*/,
        component: Input,
        params: {
          disabled: true
        }
      }, {
        dataIndex: 'paymentMethod',
        title: messages('expense-18.key20')/*付款方式类型*/,
        required: true,
        component: Select,
        params: {
          disabled: true
        },
        children: constants.paymentMethodCategory.map(item => <Option key={item.value}>{item.text}</Option>),

      }, {
        dataIndex: 'cshTransactionClassId',
        title: messages('expense-18.key21')/*付款类型*/,
        required: true,
        component: Select,
        params: {
          getPopupContainer: triggerNode => triggerNode.parentNode,
          placeholder: messages('common.please.select')/*请选择*/ /* 请选择 */
        }
      }, {
        dataIndex: 'planedPaymentDate',
        title: messages('expense-18.key10')/*计划付款日期*/,
        component: DatePicker,
        params: {
          format: 'YYYY-MM-DD',
          placeholder: messages('common.please.select')/*请选择*/
        }
      }, {
        dataIndex: 'remark',
        title: messages('common.remark')/*备注temp*/,
        component: TextArea,
        params: {
          rows: 3,
          placeholder: messages('common.please.input')/*请输入temp2*/
        },
        otherRules: [
          {
            max: 500,
            message: messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/
          }
        ]
      }
      ]
    };
  }


  componentDidMount() {
    const { payeeId } = this.props;
    this.setState({ loading: true });
    Promise.all([this.getPaymentMethodList(), this.init(), this.getBanks({payeeId})])
      .finally(() => {
        this.setState({ loading: false });
      });
  }

  init = async () => {
    const { id, form: { setFieldsValue } } = this.props;
    const { formArray } = this.state;
    if (id) {
      const ret = await paymentService.getPayInfoDetails(id);
      formArray.some(item => {
        if (item.dataIndex === 'businessCode') {
          item.params.listExtraParams.selectedPaymentScheduleId = ret.businessCode[0].id;
          return true;
        }
      });
      await this.setState({ formArray });
      await setFieldsValue({ ...ret });
    }
  };

  getPaymentMethodList = async () => {
    const { formArray } = this.state;
    const { formOID, form: { setFieldsValue }, id } = this.props;
    const ret = await expenseReportService.getApplicationPaymentMethod(formOID);
    const paymentMethodList = ret.data.loanTypes;
    const defaultMethod = ret.data.defaultLoanType;
    await this.setState({ paymentMethodList, defaultMethod });
    formArray
      .some(item => {
          if (item.dataIndex === 'cshTransactionClassId') {
            item.children = paymentMethodList.map(item => <Option
              key={item.id}>{item.description}</Option>);
            return true;
          }
        }
      );
    await this.setState({ formArray });
    if (!id) {
      await setFieldsValue({ cshTransactionClassId: (defaultMethod || {}).id });
    }
  };

  getBanks = async (expense) => {
    const { formArray } = this.state;
    const { payeeId } = expense;
    if(!payeeId) return;
    const params ={};
    params.vendorInfoId = payeeId;
    params.page = 0;
    params.size = 100;
    params.status = 1001;
    const ret = await expenseReportService.getBanks(params);
    const bankList = ret.data.venBankAccountBeans || [];
    formArray
      .some(item => {
          if (item.dataIndex === 'payeeBankAccountNumber') {
            item.children = bankList.map(item => <Option key={item.bankAccount}>{item.bankAccount}&nbsp;{item.bankName}</Option>);
            return true;
          }
        }
      );
    await this.setState({ formArray, bankList });
  };


  handleExpenseChange = async (value) => {
    const { form: { setFieldsValue } } = this.props;
    const selectedValue = value[0] || {};
    const { contractNumber: contractHeaderId, currencyCode: paymentCurrencyCode, payeeType, payeeName, accountNumber: payeeBankAccountNumber, accountName: payeeBankAccountName, paymentMethod, cshTransactionClassId, planedPaymentDate, remark, availableAmount: amount } = selectedValue;
    setFieldsValue({
      contractHeaderId,
      realPaymentAmount: { paymentCurrencyCode, amount },
      payeeType: payeeType ? payeeType + '' : void 0,
      payeeName,
      payeeBankAccountNumber,
      payeeBankAccountName,
      paymentMethod,
      cshTransactionClassId,
      planedPaymentDate: planedPaymentDate ? moment(new Date(planedPaymentDate), 'YYYY-MM-DD') : void 0,
      remark
    });
    // 需要缓存付款方式类型信息
    this.setState({paymentMethod});
    await this.getBanks(selectedValue)
  };
  // 修改银行卡需要处理付款方式类型
  handlePayeeBankAccountChange = (value) => {
    let {bankList, paymentMethod} = this.state;
    const { form: { setFieldsValue } } = this.props;
    let currentBankInfo = bankList.filter(item => item.bankAccount === value)[0];
    if (currentBankInfo.accountType === 'ALIPAY_LOGON_ID') {
      //付款方式类型 改为线上
      paymentMethod = 'ONLINE_PAYMENT';
    } else {
      paymentMethod = 'EBANK_PAYMENT';
    }
    setFieldsValue({paymentMethod, payeeBankAccountName: currentBankInfo.venBankNumberName});
  };
  handleAmountValidator = (rule, value, callback) => {
    const { form: { getFieldValue } } = this.props;
    const expense = getFieldValue('businessCode');
    if (expense && expense[0] && expense[0].availableAmount) {
      value.amount > expense[0].availableAmount ? callback(messages('expense-18.key34',{arg1: expense[0].availableAmount})/*最多可申请支付额度：{arg1}*/) : callback();
    }
    if(value.amount === 0) {
      callback(messages('expense-18.key35')/*金额不可为0*/)
    }
    callback();
  };

  handleSubmit = () => {
    const { form: { validateFieldsAndScroll }, paymentRequestOID, id } = this.props;
    validateFieldsAndScroll(async (errors, values) => {
      if (!errors) {
        await this.setState({ loading: true });
        try {
          await paymentService.addPaymentPayLine(values, paymentRequestOID, id);
          message.success(messages('common.operate.success')/*操作成功*/);
          this.props.close(true);
        } catch (e) {

        }
        await this.setState({ loading: false });
      }
    });
  };

  handleCancel = () => {
    this.props.close();
  };

  render() {
    const { loading, formArray } = this.state;
    const { form: { getFieldDecorator } } = this.props;
    const formItemLayout = { labelCol: { span: 7 }, wrapperCol: { span: 15, offset: 1 } };
    return (
      <section className="new-pay-info">
        <Form className="new-form">
          <Spin spinning={loading}>
            {
              formArray.map(item => {
                return (
                  <Form.Item  {...formItemLayout} extra={item.extra} label={item.title}>
                    {
                      getFieldDecorator(item.dataIndex, {
                        rules: Object.assign([{
                          required: item.required,
                          message: messages('common.please.input')/*请输入temp2*/ + item.title
                        }], item.otherRules),
                        initialValue: item.initialValue,
                        valuePropName: item.valuePropName || 'value'
                      })(React.createElement(item.component, item.params, item.children || null))
                    }
                  </Form.Item>
                );
              })
            }
          </Spin>
          <Affix offsetBottom={0} className="slide-footer">
            <Button
              type="primary"
              loading={loading}
              htmlType="submit"
              onClick={this.handleSubmit}
            >
              {messages('common.save')/*保存*/}
            </Button>
            <Button
              onClick={this.handleCancel}
              className="new-unit-cancel"
            >
              {messages('common.cancel')/*取消*/}
            </Button>
          </Affix>
        </Form>
      </section>
    );
  }
}

NewPayInfo.propTypes = {};

export default NewPayInfo;
